package com.lab.schemeurl;

import android.content.Context;
import android.net.Uri;
import android.webkit.WebView;

import com.cuitrip.business.webview.proxy.WebViewProxy;
import com.lab.logtrack.AppLog;
import com.lab.schemeurl.constant.Host;
import com.lab.schemeurl.constant.Scheme;


/**
 * Created by ak
 * 全局共享使用的
 */
public class SchemeUrlHandler {

    public static final String PARAMETER_ACTION = "action";
    public static final String PARAMETER_POSITIPN = "position";

    private static SchemeUrlHandler sInstance;

    private SchemeUrlHandler() {
        this.mSchemeUrlDispatcher = new SchemeUrlDispatcher(mSchemeUrlHandler);
    }

    public static SchemeUrlHandler getInstance() {
        if (null == sInstance)
            sInstance = new SchemeUrlHandler();
        return sInstance;
    }

    private SchemeUrlDispatcher mSchemeUrlDispatcher;
    private SchemeUrlDispatcher.ISchemeUrlHandler mSchemeUrlHandler = new SchemeUrlDispatcher.ISchemeUrlHandler() {
        @Override
        public boolean onSchemeUrlHandle(Context context, Uri uri, Scheme scheme, Host host) {

            try {
                boolean result = false;
                if (null != uri && null != scheme) {
                    if (scheme == Scheme.CUITRIP && null != host) {
                        result = host.perform(context, uri, mSchemeUrlDispatcher);
                        if (!result) {
//                            ToastUtil.toast("unhandled url");
                            result = true;//scheme url无论如何都处理结束，不继续传递
                        }
                    } else if (scheme == Scheme.HTTP) {
                        WebViewProxy.getInstance().browseWeb(context, uri.toString());
                        result = true;
                    }
                }
                return result;
            } catch (Throwable e) {
                //catch all
                e.printStackTrace();
                AppLog.e(e);
            }
            return true;
        }


    };

    public boolean dispatch(Uri uri) {
        return mSchemeUrlDispatcher.dispatch(null, uri, null);
    }

    public boolean dispatch(Context context, Uri uri) {
        return mSchemeUrlDispatcher.dispatch(context, uri, null);
    }

    public boolean dispatch(Uri uri, WebView webView) {
        return mSchemeUrlDispatcher.dispatch(null, uri, webView);
    }

    public boolean dispatch(Context context, Uri uri, WebView webView) {
        return mSchemeUrlDispatcher.dispatch(context, uri, webView);
    }

    public boolean isAppScheme(String url){
        Uri uri = Uri.parse(url);
        Scheme scheme = Scheme.getSchemeByName(uri.getScheme());
        if (scheme.equals(Scheme.CUITRIP)){
            return true;
        }
        return false;
    }


}
